﻿using System;
using SPCAF.Sdk;
using SPCAF.Sdk.Model;
using SPCAF.Sdk.Rules;
using SPCAFContrib.Entities.Consts;
using SPCAFContrib.Extensions;
using SPCAFContrib.Groups;

namespace SPCAFContrib.Rules.Control
{
    [RuleMetadata(typeof(ContribCorrectnessGroup),
     CheckId = CheckIDs.Rules.ASCXFile.SetAutoGenerateColumnsForSPGridViewInControl,
     Help = CheckIDs.Rules.ASCXFile.SetAutoGenerateColumnsForSPGridViewInControl_HelpUrl,

     Message = "Set AutoGenerateColumns=false for SPGridView in the user contol [{0}].",
     DisplayName = "Set AutoGenerateColumns=false for SPGridView in the user contol.",
     Description = "The SPGridView control does not support the automatic generation of columns.",
     Resolution = "You always have to set the property AutoGenerateColumns to false and explicitly bind your columns using SPBoundField.",

     DefaultSeverity = Severity.Error,
     SharePointVersion = new[] { "12","14", "15" },
     Links = new[]
     {
         "SPGridView class",
         "http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webcontrols.spgridview.aspx"
     }
     )]
    public class SetAutoGenerateColumnsForSPGridViewInControl : Rule<ASCXFile>
    {
        #region methods

        public override void Visit(ASCXFile target, NotificationCollection notifications)
        {
            target.FindControl("SPGridView", (controlDeclaration, lineNumber, linePosition) =>
            {
                if (controlDeclaration.IndexOf(" AutoGenerateColumns", StringComparison.InvariantCultureIgnoreCase) == -1 ||
                    controlDeclaration.IndexOf(" AutoGenerateColumns=\"true\"", StringComparison.InvariantCultureIgnoreCase) > 0)
                    Notify(target, String.Format(this.MessageTemplate(), target.ReadableElementName),
                                        target.GetSummaryWithLineInfo(lineNumber, linePosition),
                                        notifications);
            });
        }

        #endregion
    }
}
